package com.czkt.springboot_mybatis_test.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czkt.springboot_mybatis_test.entity.*;
import com.czkt.springboot_mybatis_test.entity.vo.RoleRight;
import com.czkt.springboot_mybatis_test.service.ISysRightService;
import com.czkt.springboot_mybatis_test.service.ISysRoleRightService;
import com.czkt.springboot_mybatis_test.service.ISysRoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2024-06-18
 */
@Controller
@RequestMapping("/springboot_mybatis_test/sys-role-right")
public class SysRoleRightController {
    @Resource
    ISysRoleService roleService;

    @Resource
    ISysRightService rightService;

    @Resource
    ISysRoleRightService roleRightService;

    @RequestMapping("/role/edit")
    public String updateRole(String roleId,Model model){
        SysRole sysRole = roleService.getById(roleId);
        List<SysRight> roleRights = roleRightService.roleRight(roleId);
        model.addAttribute("role",sysRole);
        model.addAttribute("rights",rightService.list());
        model.addAttribute("roleRights",roleRights);
        return "/role/edit";
    }

    @RequestMapping("/role/save")
    public String toUpdateRole(SysRole sysRole,@RequestParam("rightCodes") String[] rightCodes){
        roleRightService.updateRoleId(sysRole);
        roleRightService.deleteByRfRoleId(sysRole.getRoleId());
        for (int i = 0; i < rightCodes.length; i++) {
            roleRightService.insertRfRoleId(sysRole.getRoleId(),rightCodes[i]);
        }
        return "redirect:/springboot_mybatis_test/sys-role/crm/role/list";
    }

    @RequestMapping("/crm/role/del/{roleId}")
    @ResponseBody
    public Object deleteRoleId(@PathVariable("roleId") String roleId){
        Map<String,Object> map = new HashMap<>();
        SysRoleRight sysRoleRight = roleRightService.selectByRfRoleId(roleId);
        if(sysRoleRight != null){
            roleRightService.delByRfId(roleId);
            roleRightService.deleteByRfRoleId(roleId);
        }else {
            roleRightService.deleteByRfRoleId(roleId);
        }
        map.put("delResult","true");
        return map;
    }
}
